{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# USAD-LSTM在SMAP和MSL数据集上实验"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/user/miniconda3/envs/yjq-ml/lib/python3.10/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
      "  from .autonotebook import tqdm as notebook_tqdm\n"
     ]
    }
   ],
   "source": [
    "from usadlstm_model import *\n",
    "import sys\n",
    "sys.path.append('../common/')\n",
    "from evaluator import *\n",
    "import warnings\n",
    "import os\n",
    "import numpy as np\n",
    "import torch\n",
    "from torch.utils.data import DataLoader\n",
    "from torch.utils.data.sampler import SubsetRandomSampler\n",
    "warnings.filterwarnings(\"ignore\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def convert_to_windows(data, window_size):\n",
    "    windows = []\n",
    "    length  = data.shape[0]\n",
    "    for i in range(length):\n",
    "        if length - i >= window_size:\n",
    "            window = data[i:i+window_size]\n",
    "        else:\n",
    "            window = data[i-window_size+1:i+1]\n",
    "        windows.append(window)    \n",
    "    return np.array(windows)\n",
    "\n",
    "def load_dataset(dataset, machine, window_size):\n",
    "    folder = os.path.join(\"../../processed\", dataset)\n",
    "    if not os.path.exists(folder):\n",
    "        raise Exception(\"Processed Data not found.\")\n",
    "    loader = []\n",
    "    for file in [\"train\", \"test\", \"labels\"]:\n",
    "        file = machine + \"_\" + file\n",
    "        loader.append(np.load(os.path.join(folder, f\"{file}.npy\")))\n",
    "    ## 准备数据\n",
    "    train_data = convert_to_windows(loader[0], window_size)\n",
    "    test_data = convert_to_windows(loader[1], window_size)\n",
    "    labels = np.zeros((loader[2].shape[0], 1))\n",
    "    for i, row in enumerate(loader[2]):\n",
    "        if np.any(row == 1):\n",
    "            labels[i] = 1   \n",
    "        \n",
    "    return (train_data, test_data, labels)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## SMAP"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "window_size = 5\n",
    "batch_size = 32\n",
    "num_epochs = 5\n",
    "z_dim = 32"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "origin_file_list = os.listdir(\"../processed/SMAP\")\n",
    "file_name_set = set()\n",
    "for origin_file in origin_file_list:\n",
    "    file_name_set.add(origin_file.split(\"_\")[0])\n",
    "file_name_list = list(file_name_set)\n",
    "file_name_list.sort()\n",
    "datas = {}\n",
    "for file_name in file_name_list:\n",
    "    train_data, test_data, labels = load_dataset(\"SMAP\", file_name, window_size)\n",
    "    datas[file_name] = (train_data, test_data, labels)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "A-1\n",
      "(2880, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:11<00:00,  2.38s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "A-2\n",
      "(2648, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:11<00:00,  2.27s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "A-3\n",
      "(2736, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:10<00:00,  2.08s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "A-4\n",
      "(2690, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:10<00:00,  2.17s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "A-5\n",
      "(705, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:02<00:00,  1.72it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "A-6\n",
      "(682, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:02<00:00,  1.81it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "A-7\n",
      "(2879, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:11<00:00,  2.34s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "A-8\n",
      "(762, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:02<00:00,  1.74it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "A-9\n",
      "(762, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:03<00:00,  1.54it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "B-1\n",
      "(2435, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:09<00:00,  2.00s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "D-1\n",
      "(2849, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:10<00:00,  2.12s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "D-11\n",
      "(2611, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:10<00:00,  2.04s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "D-12\n",
      "(312, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:01<00:00,  4.06it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "D-13\n",
      "(1490, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:06<00:00,  1.33s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "D-2\n",
      "(2880, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:11<00:00,  2.38s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "D-3\n",
      "(2880, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:11<00:00,  2.37s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "D-4\n",
      "(2833, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:10<00:00,  2.16s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "D-5\n",
      "(2561, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:10<00:00,  2.11s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "D-6\n",
      "(2594, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:10<00:00,  2.15s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "D-7\n",
      "(2583, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:11<00:00,  2.33s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "D-8\n",
      "(2602, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:11<00:00,  2.21s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "D-9\n",
      "(2583, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:09<00:00,  1.98s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "E-1\n",
      "(2880, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:12<00:00,  2.57s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "E-10\n",
      "(2880, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:13<00:00,  2.60s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "E-11\n",
      "(2880, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:11<00:00,  2.34s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "E-12\n",
      "(2880, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:13<00:00,  2.63s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "E-13\n",
      "(2880, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:12<00:00,  2.46s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "E-2\n",
      "(2880, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:11<00:00,  2.35s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "E-3\n",
      "(2880, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:12<00:00,  2.51s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "E-4\n",
      "(2880, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:13<00:00,  2.66s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "E-5\n",
      "(2880, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:13<00:00,  2.73s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "E-6\n",
      "(2880, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:13<00:00,  2.63s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "E-7\n",
      "(2769, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:13<00:00,  2.69s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "E-8\n",
      "(2880, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:12<00:00,  2.59s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "E-9\n",
      "(2880, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:12<00:00,  2.42s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "F-1\n",
      "(2869, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:13<00:00,  2.61s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "F-2\n",
      "(2861, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:10<00:00,  2.19s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "F-3\n",
      "(2880, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:10<00:00,  2.08s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "G-1\n",
      "(2820, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:10<00:00,  2.12s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "G-2\n",
      "(2478, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:10<00:00,  2.01s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "G-3\n",
      "(2624, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:09<00:00,  1.94s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "G-4\n",
      "(2551, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:09<00:00,  1.83s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "G-6\n",
      "(2881, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:10<00:00,  2.10s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "G-7\n",
      "(2446, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:08<00:00,  1.77s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "P-1\n",
      "(2872, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:10<00:00,  2.08s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "P-2\n",
      "(2821, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:09<00:00,  1.95s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "P-3\n",
      "(2855, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:10<00:00,  2.03s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "P-4\n",
      "(2609, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:09<00:00,  1.97s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "P-7\n",
      "(2853, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:10<00:00,  2.14s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "R-1\n",
      "(2874, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:09<00:00,  1.98s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "S-1\n",
      "(2818, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:09<00:00,  1.94s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "T-1\n",
      "(2875, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:09<00:00,  1.94s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "T-2\n",
      "(2855, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:09<00:00,  1.98s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "T-3\n",
      "(2876, 5, 25)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:10<00:00,  2.12s/it]\n"
     ]
    }
   ],
   "source": [
    "train_gaussian_percentage = 0.2\n",
    "\n",
    "results = {}\n",
    "for machine in file_name_list:\n",
    "    print(machine) \n",
    "    train_window,test_window,labels = datas[machine]\n",
    "    print(train_window.shape)\n",
    "    train_dataset = torch.from_numpy(train_window).float().view([train_window.shape[0], \n",
    "                                     train_window.shape[1]*train_window.shape[2]])\n",
    "    test_dataset = torch.from_numpy(test_window).float().view([test_window.shape[0], \n",
    "                                     test_window.shape[1]*test_window.shape[2]])\n",
    "       # 每个模型单独训练\n",
    "    model = UsadLSTM(train_window.shape[2]*window_size, z_dim)\n",
    "    model.to(get_default_device())\n",
    "    indices = np.random.permutation(len(train_dataset))\n",
    "    split_point = int(train_gaussian_percentage * len(train_dataset))\n",
    "\n",
    "    \n",
    "    train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, drop_last=True,\n",
    "                              sampler=SubsetRandomSampler(indices[:-split_point]), pin_memory=False)\n",
    "    val_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, drop_last=True,\n",
    "                                       sampler=SubsetRandomSampler(indices[-split_point:]), pin_memory=False)\n",
    "    test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False, drop_last=False)\n",
    "\n",
    "\n",
    "    history = model.fit(train_loader=train_loader,validation_loader=val_loader,epochs=num_epochs)\n",
    "    pred= model.predict_prob(test_loader, alpha=0.9, beta=0.1)\n",
    "    result = bf_search(labels.flatten(), pred, verbose=False)\n",
    "    results[machine] =result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "precision mean: 0.828\n",
      "recall mean: 0.9925\n",
      "f1 mean: 0.8746\n",
      "f1* mean: 0.9028\n"
     ]
    }
   ],
   "source": [
    "f1_scores = [item['f1-score'] for item in list(results.values())]\n",
    "precisions = [item['precision'] for item in list(results.values())]\n",
    "recalls = [item['recall'] for item in list(results.values())]\n",
    "TNs = [item['TN'] for item in list(results.values())]\n",
    "TPs = [item['TP'] for item in list(results.values())]\n",
    "FNs = [item['FN'] for item in list(results.values())]\n",
    "FPs = [item['FP'] for item in list(results.values())]\n",
    "f1_mean = round(np.mean(f1_scores).item(),4)\n",
    "precision_mean = round(np.mean(precisions),4)\n",
    "recall_mean = round(np.mean(recalls),4)\n",
    "f1_star = round(2 * precision_mean * recall_mean / (precision_mean + recall_mean + 0.00001),4)\n",
    "print(f\"precision mean: {precision_mean}\")\n",
    "print(f\"recall mean: {recall_mean}\")\n",
    "print(f\"f1 mean: {f1_mean}\")\n",
    "print(f\"f1* mean: {f1_star}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## MSL"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "window_size = 5\n",
    "batch_size = 64\n",
    "num_epochs = 5\n",
    "z_dim = 32"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "origin_file_list = os.listdir(\"../processed/MSL\")\n",
    "file_name_set = set()\n",
    "for origin_file in origin_file_list:\n",
    "    file_name_set.add(origin_file.split(\"_\")[0])\n",
    "file_name_list = list(file_name_set)\n",
    "file_name_list.sort()\n",
    "datas = {}\n",
    "for file_name in file_name_list:\n",
    "    train_data, test_data, labels = load_dataset(\"MSL\", file_name, window_size)\n",
    "    datas[file_name] = (train_data, test_data, labels)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "C-1\n",
      "(2158, 5, 55)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:05<00:00,  1.14s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "C-2\n",
      "(764, 5, 55)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:02<00:00,  2.41it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "D-14\n",
      "(3675, 5, 55)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:10<00:00,  2.12s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "D-15\n",
      "(2074, 5, 55)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:05<00:00,  1.09s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "D-16\n",
      "(1451, 5, 55)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:04<00:00,  1.19it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "F-4\n",
      "(2244, 5, 55)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:06<00:00,  1.31s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "F-5\n",
      "(2598, 5, 55)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:07<00:00,  1.60s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "F-7\n",
      "(2511, 5, 55)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:07<00:00,  1.48s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "F-8\n",
      "(3342, 5, 55)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:10<00:00,  2.01s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "M-1\n",
      "(2209, 5, 55)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:05<00:00,  1.18s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "M-2\n",
      "(2208, 5, 55)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:06<00:00,  1.22s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "M-3\n",
      "(2037, 5, 55)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:05<00:00,  1.12s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "M-4\n",
      "(2076, 5, 55)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:06<00:00,  1.29s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "M-5\n",
      "(2032, 5, 55)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:06<00:00,  1.23s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "M-6\n",
      "(1565, 5, 55)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:04<00:00,  1.21it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "M-7\n",
      "(1587, 5, 55)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:04<00:00,  1.16it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "P-10\n",
      "(4308, 5, 55)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:12<00:00,  2.54s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "P-11\n",
      "(3969, 5, 55)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:11<00:00,  2.37s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "P-14\n",
      "(2880, 5, 55)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:08<00:00,  1.61s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "P-15\n",
      "(3682, 5, 55)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:10<00:00,  2.15s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "S-2\n",
      "(926, 5, 55)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:02<00:00,  2.03it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "T-12\n",
      "(1145, 5, 55)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:03<00:00,  1.53it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "T-13\n",
      "(1145, 5, 55)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:03<00:00,  1.56it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "T-4\n",
      "(2272, 5, 55)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:06<00:00,  1.25s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "T-5\n",
      "(2272, 5, 55)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:06<00:00,  1.33s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "T-8\n",
      "(748, 5, 55)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:02<00:00,  2.31it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "T-9\n",
      "(439, 5, 55)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5/5 [00:01<00:00,  4.37it/s]\n"
     ]
    }
   ],
   "source": [
    "train_gaussian_percentage = 0.2\n",
    "\n",
    "results = {}\n",
    "for machine in file_name_list:\n",
    "    print(machine) \n",
    "    train_window,test_window,labels = datas[machine]\n",
    "    print(train_window.shape)\n",
    "    train_dataset = torch.from_numpy(train_window).float().view([train_window.shape[0], \n",
    "                                     train_window.shape[1]*train_window.shape[2]])\n",
    "    test_dataset = torch.from_numpy(test_window).float().view([test_window.shape[0], \n",
    "                                     test_window.shape[1]*test_window.shape[2]])\n",
    "       # 每个模型单独训练\n",
    "    model = UsadLSTM(train_window.shape[2]*window_size, z_dim)\n",
    "    model.to(get_default_device())\n",
    "    indices = np.random.permutation(len(train_dataset))\n",
    "    split_point = int(train_gaussian_percentage * len(train_dataset))\n",
    "\n",
    "    \n",
    "    train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, drop_last=True,\n",
    "                              sampler=SubsetRandomSampler(indices[:-split_point]), pin_memory=False)\n",
    "    val_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, drop_last=True,\n",
    "                                       sampler=SubsetRandomSampler(indices[-split_point:]), pin_memory=False)\n",
    "    test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False, drop_last=False)\n",
    "\n",
    "\n",
    "    history = model.fit(train_loader=train_loader,validation_loader=val_loader,epochs=num_epochs)\n",
    "    pred= model.predict_prob(test_loader, alpha=0.5, beta=0.5)\n",
    "    result = bf_search(labels.flatten(), pred, verbose=False)\n",
    "    results[machine] =result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "precision mean: 0.8852\n",
      "recall mean: 0.9756\n",
      "f1 mean: 0.92\n",
      "f1* mean: 0.9282\n"
     ]
    }
   ],
   "source": [
    "f1_scores = [item['f1-score'] for item in list(results.values())]\n",
    "precisions = [item['precision'] for item in list(results.values())]\n",
    "recalls = [item['recall'] for item in list(results.values())]\n",
    "TNs = [item['TN'] for item in list(results.values())]\n",
    "TPs = [item['TP'] for item in list(results.values())]\n",
    "FNs = [item['FN'] for item in list(results.values())]\n",
    "FPs = [item['FP'] for item in list(results.values())]\n",
    "f1_mean = round(np.mean(f1_scores).item(),4)\n",
    "precision_mean = round(np.mean(precisions),4)\n",
    "recall_mean = round(np.mean(recalls),4)\n",
    "f1_star = round(2 * precision_mean * recall_mean / (precision_mean + recall_mean + 0.00001),4)\n",
    "print(f\"precision mean: {precision_mean}\")\n",
    "print(f\"recall mean: {recall_mean}\")\n",
    "print(f\"f1 mean: {f1_mean}\")\n",
    "print(f\"f1* mean: {f1_star}\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "yjq-3.6",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
